import os

import numpy as np
import pandas as pd

from app.agent.factors.factor_lib import momentum_shift

# bar结构化数组定义
dtype = [('time', np.int64), ('open', float), ('high', float), ('low', float), ('close', float)]

bars = np.zeros(500, dtype=dtype)

import polars as pl

bs_num = {"B": 0, "S": 0}  # 买卖单的数量
bs_price = {"B": None, "S": None}  # 买卖单的价格


def validate_factor() -> float:
    profit = 0
    symbol = "USDCNHSP"
    file_path = os.path.join("data", symbol, f"{symbol}_BAR_60N.parquet")
    i = 0
    for tick in pl.read_parquet(file_path, use_pyarrow=True, memory_map=True).iter_rows():
        if i > 1000:
            break

        # print(tick)
        bars[:-1] = bars[1:]
        bars[-1] = tick[1], tick[4], tick[5], tick[6], tick[7]
        i += 1
        if i <= 500:
            continue
        else:
            close = bars['close']
            high = bars['high']
            low = bars['low']
            open = bars['open']
            if buy(open, high, low, close):
                print("买入")
                if bs_num["S"] == 1:
                    profit += bs_price["S"] - close[-1]
                    bs_num["S"] = 0
                    print("buy == 0  profit: ", profit)

                elif bs_num["B"] == 0:
                    print("buy ==1 ", )
                    bs_num["B"] = 1
                    bs_price["B"] = close[-1]
                else:
                    print("不满足 buy 得条件")
                    continue

            if sell(open, high, low, close):
                if bs_num["B"] == 1:
                    profit += close[-1] - bs_price["B"]
                    bs_num["B"] = 0
                    print("sell == 0 profit: ", profit)
                elif bs_num["S"] == 0:
                    print("sell ==1 ", )
                    bs_num["S"] = 1
                    bs_price["S"] = close[-1]
                else:
                    print("不满足 sell 得条件")

                    continue
    print("bar", i)
    return profit


def buy(open, high, low, close) -> bool:
    arr = np.array([open, high, low,close])
    if arr.all():
        close_price = pd.Series(close)
        rank = momentum_shift(close_price)
        return rank.iloc[-1] > 10
    # rsi = ta.RSI(close, 11)
    # return rsi[-1] > 70
    return False


def sell(open, high, low, close) -> bool:
    # rsi = ta.RSI(close, 11)
    # return rsi[-1] < 30
    return True


# print(validate_factor())
